<template>
	<view>
		<uni-nav-bar @clickLeft="toBack" color="#555" leftIcon="arrowleft" :title="username.nickName" :fixed="true" :status-bar="true"></uni-nav-bar>
		<chat id="chat" ref="chat" :username="username" chatType="singleChat"></chat>
	</view>
</template>

<script>
let disp = require('../../utils/broadcast');
import chat from '@/components/chat/chat.vue';
import Constant from '../../utils/Constant.js';
export default {
	components: {
		chat
	},
	data() {
		return {
			username: {
				your: ''
			}
		};
	},
	onLoad(options) {
		let user = JSON.parse(options.user);
		this.username = user;
	},
	onUnload() {
		disp.fire('em.chatroom.leave');
		this.readMessage();
	},
	methods: {
		toBack(){
			uni.navigateBack({
			    delta: 1
			});
		},
		readMessage(){
			let user = uni.getStorageSync(Constant.user);
			let sessionKey = this.username.userId + user.accountNo;
			let historyChatMsgs = uni.getStorageSync('rendered_' + sessionKey) || [];
			if(historyChatMsgs.length>0){
				let mesg = historyChatMsgs[historyChatMsgs.length-1];
				this.username.updateTime = Date.now();
				this.username.readStatus = true;
				this.username.unreadCount = 0;
				this.username.messageType = mesg.msg.data[0].type;
				this.username.lastMessage = mesg.msg.data[0].data;
				let userArr =  uni.getStorageSync(Constant.userFriend)||[];
				let index = userArr&&userArr.findIndex(muser=>{
					return muser.userId === this.username.userId;
				});
				if(index>-1){
					userArr.splice(index,1);
					userArr.unshift(this.username);
					uni.setStorageSync(Constant.userFriend,userArr);
				}
			}
		}
	},
	onPullDownRefresh: function () {
	  uni.showNavigationBarLoading();
	  this.$refs.chat.getMore();
	  // 停止下拉动作
	  uni.hideNavigationBarLoading();
	  uni.stopPullDownRefresh();
	}
};
</script>

<style>
page {
	background-color: #fafafa;
	height: 100%;
}
</style>
